import React from 'react'
import { Tag,Space } from 'antd'
import { useSelector } from 'react-redux'
import { closeTab,setCurrentMenu } from '../../store/reducer/tab'
import { useDispatch } from 'react-redux'
import { useLocation,useNavigate } from 'react-router-dom'

import './index.css'

export default function CommonTag() {

    const tabList = useSelector(state => state.tab.tabList)
    const currentMenu = useSelector(state => state.tab.currentMenu)
    const dispatch = useDispatch()
    const action = useLocation()
    const navigate=useNavigate()

    const handleClose=(tag,index)=>{
        // console.log(tabList);
        let length = tabList.length - 1
        dispatch(closeTab(tag))
        // 如果关闭的不是当前的tag
        if(tag.path !== action.pathname){
            return 
        }
        // 删除的是最末位的tag
        if(index===length){
            // 设置当前数据
            const curData = tabList[index-1]
            dispatch(setCurrentMenu(curData))
            navigate(curData.path)
        }else{
            // 如果tag至少存在一个数据，则选择后一个tag
            if(tabList.length>1){
                // 下一个tag
                const nextData = tabList[index+1]
                dispatch(setCurrentMenu(nextData))
                navigate(nextData.path)
            }
        }
    }

    // 点击Tag
    const handleChange=(tag)=>{
        dispatch(setCurrentMenu(tag))
        navigate(tag.path)
    }

    // tag的显示
    const setTag = (flag,item,index)=>{
        return (
            flag ? 
            <Tag key={item.name} color='#55acee' closeIcon onClose={()=>handleClose(item,index)}>{item.label}</Tag>
            :
            <Tag key={item.name} onClick={()=>handleChange(item)}>{item.label}</Tag>
        )
    }

  return (
    <Space className='common-tag' size={[0,8]} wrap>
        {/* <Tag>首页</Tag>
        <Tag color="#55acee" closeIcon onClose={()=>{handleClose()}}>
            用户列表
        </Tag> */}
        {
            currentMenu.name && tabList.map((item,index)=>setTag(item.path===currentMenu.path,item,index))
        }
    </Space>
  )
}
